package com.cjm.algorithm.queue;

import java.util.ArrayDeque;
import java.util.Deque;

public class ReverseParentheses1190 {
    public String reverseParentheses(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }
        Deque<Character> queue = new ArrayDeque<>();
        queue.addLast(s.charAt(0));
        for (int i = 1; i < s.length(); i++) {
            Character c = s.charAt(i);
            if (Character.valueOf(')').equals(c)) {
                Deque<Character>  temp = new ArrayDeque<>();
                while (true) {
                    Character c1 = queue.pollLast();
                    if (Character.valueOf('(').equals(c1)) {
                        break;
                    }
                    temp.addLast(c1);
                }
                while (!temp.isEmpty()) {
                    queue.addLast(temp.pollFirst());
                }
            } else {
                queue.addLast(c);
            }
        }
        StringBuilder sb = new StringBuilder();
        while (!queue.isEmpty()) {
            sb.append(queue.pollFirst());
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        ReverseParentheses1190 xx = new ReverseParentheses1190();
        System.err.println(xx.reverseParentheses("a(bcdefghijkl(mno)p)q"));
    }
}
